from PIL import Image
import subprocess
import os

ffmpeg = "H:/RareWolf_Toolkit/Package/ffmpeg/ffmpeg.exe"

def add_watermark_with_opacity(image_path, video_path, output_path, opacity):

    image = Image.open(image_path)
    '''
    #剪切尺寸
    target_size = (1920, 1080)  # 要剪切的目标尺寸
    # 计算图像的宽度和高度
    width, height = image.size
    # 计算剪切的起始位置
    left = (width - target_size[0]) // 2
    top = (height - target_size[1]) // 2
    # 计算剪切的结束位置
    right = left + target_size[0]
    bottom = top + target_size[1]
    # 使用 crop() 方法剪切图像
    image.crop((left, top, right, bottom))
    '''


    '''
    #缩放尺寸
    image = Image.open("C:/Users/QL_001/Desktop/text/给钱.png")
    new_size = (1920, 1080)  # 设置新的尺寸，格式为 (宽度, 高度)
    resized_image = image.resize(new_size)
    resized_image.save("C:/Users/QL_001/Desktop/text/temp_watermark.png")
    '''

    if image.mode in ("RGBA", "LA") or (image.mode == "P" and "transparency" in image.info):
        image = image.convert("RGBA")
        data = image.getdata()
        new_data = []
        for item in data:
            #new_data.append((item[0], item[1], item[2], int(opacity * 255)))  # 设置新的透明度
            new_data.append((*item[:3], int(item[3] * opacity)))
        image.putdata(new_data)
   
    temp_watermark_path = "C:/Users/QL_001/Desktop/text/temp_watermark.png"
    image.save(temp_watermark_path)

    # 获取原有的视频编码格式
    ffprobe_cmd = f'{ffmpeg} -i "{video_path}"'
    result = subprocess.run(
        ffprobe_cmd, 
        capture_output=True, 
        text=True, 
        shell=True
    )
    video_info = result.stderr

    # 添加水印到视频
    #ffmpeg_cmd = f'{ffmpeg} -i "{video_path}" -i "{temp_watermark_path}" -filter_complex "overlay=(main_w-overlay_w)/2:(main_h-overlay_h)/2" "{output_path}"'
    ffmpeg_cmd = f'{ffmpeg} -i "{video_path}" -i "{temp_watermark_path}" -filter_complex "overlay=(main_w-overlay_w)/2:(main_h-overlay_h)/2" -crf 0 "{output_path}"'
    ffmpeg_cmd = f'{ffmpeg} -i "{video_path}" -i "{temp_watermark_path}" -filter_complex "overlay=(main_w-overlay_w)/2:(main_h-overlay_h)/2" -c:v {video_info} -c:a copy "{output_path}"'
    
    subprocess.call(ffmpeg_cmd, shell=True)
    
    # 删除临时文件
    os.remove(temp_watermark_path)
pic = "C:/Users/QL_001/Desktop/text/给钱.png"
input = "C:/Users/QL_001/Desktop/text/EP024_sc001_shot014a.mov"
output = "C:/Users/QL_001/Desktop/text/output_video.mov"
# 调用add_watermark_with_opacity函数来添加带有调整透明度的水印
add_watermark_with_opacity(pic, input, output, 0.01)# 设置透明度，范围从 0（完全透明）到 1（完全不透明）